package com.invengo.testrfid.mvp.presenter;

import android.app.Application;
import android.content.Context;
import android.widget.TextView;

import com.invengo.testrfid.app.dao.QueryManager;
import com.invengo.testrfid.app.dao.RfidCageBind;
import com.invengo.testrfid.app.entity.MessageEntity;
import com.invengo.testrfid.app.entity.ReadTagEntity;
import com.invengo.testrfid.app.proxy.ProxyNetWorker;
import com.invengo.testrfid.app.proxy.ProxyReadTag;
import com.invengo.testrfid.app.utils.ByteConvertUtils;
import com.invengo.testrfid.app.utils.Constant;
import com.invengo.testrfid.app.utils.GsonUtils;
import com.invengo.testrfid.app.utils.MyLogUtils;
import com.invengo.testrfid.app.utils.SoundPlayUtils;
import com.invengo.testrfid.app.utils.TimeUtilsNew;
import com.invengo.testrfid.app.utils.UUIDUtils;
import com.invengo.testrfid.app.utils.WifiStatueUtils;
import com.invengo.testrfid.mvp.contract.AddCageContract;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;

import javax.inject.Inject;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;


@ActivityScope
public class AddCagePresenter extends BasePresenter<AddCageContract.Model, AddCageContract.View> {

    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    /**
     * Tid 1
     */
    private TextView Tid1;

    /**
     * TID 2
     */
    private TextView Tid2;

    private QueryManager queryManager;
    private Context context;

    @Inject
    public AddCagePresenter(AddCageContract.Model model, AddCageContract.View rootView) {
        super(model, rootView);
        queryManager = QueryManager.getManager();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
        this.queryManager = null;
    }

    public void initContext(Context context, TextView tid1, TextView tid2) {

        this.Tid1 = tid1;
        this.Tid2 = tid2;
        this.context = context;
    }

    public void connectReader() {

        ProxyReadTag.getInstance().connectReader(new ProxyReadTag.ConnectReaderStatue() {
            @Override
            public void onConnectSuccess() {

                mRootView.showMessage("读写器连接成功");
            }

            @Override
            public void onConnectFailed() {

                mRootView.showMessage("读写器连接失败");
            }
        });
    }

    /**
     * 断开连接
     */
    public void disConnectReader() {

        ProxyReadTag.getInstance().disConnectReader(new ProxyReadTag.DisConnectReaderStatue() {
            @Override
            public void onDisConnectSuccess() {

            }

            @Override
            public void onDisConnectFailed() {

            }
        });

    }

    public void readTagTid() {

        if (!Tid1.getText().toString().contains("Tid1") && !Tid2.getText().toString().contains("Tid2")) {

//            SoundPlayUtils.getInstance().playSound(SoundPlayUtils.SOUNT_SUCCESS, 0);
            mRootView.showMessage("两个标签都已绑定，如要修改；请点击标签后边的按钮，删除其中一个标签数据");
//            return;
        }

        ProxyReadTag.getInstance().readTagAllData(new ProxyReadTag.ReadTagAllDataCallbac() {
            @Override
            public void onReadTagSuccess(ReadTagEntity readTagEntity) {

                handTid(readTagEntity.getTid(),readTagEntity.getEpc());

                MyLogUtils.log(Constant.ValueOfTag_ADD,readTagEntity.getEpc(),3);
            }

            @Override
            public void onReadTagFailed(String msg) {
                mRootView.showMessage(msg);
            }
        });
    }


    private void handTid(String tid,String epc) {

        // 该标签已绑定，显示失败信息
        RfidCageBind rfidCageBind = queryManager.getRfidCageQuery().queryDataByTid(tid);


        if (Tid1.getText().toString().contains(tid)) {
            mRootView.initTid(tid,epc);
            return;
        }

        if (Tid2.getText().toString().contains(tid)) {
            mRootView.initTidSecond(tid,epc);
            return;
        }

        if (rfidCageBind != null) {

            mRootView.showMessage("该标签已绑定，请更换标签！");
            return;
        }

        if (Tid1.getText().toString().contains("Tid1")
                || Tid1.getText().toString().equals(tid)) {

            Tid1.setText(tid);
            mRootView.initTid(tid,epc);
        } else if (Tid2.getText().toString().contains("Tid2")
                && !Tid1.getText().toString().contains(tid)) {

            Tid2.setText(tid);
            mRootView.initTidSecond(tid,epc);
        } else {

            // 先不进行焦点的提示
//            mRootView.requestFocus();
        }


    }

    public void stopReadTag() {

        ProxyReadTag.getInstance().stopRead(new ProxyReadTag.StopReadCallback() {

            @Override
            public void onStopSuccess() {

            }

            @Override
            public void onStopFailed() {

                mRootView.showMessage("停止读取标签操作失败，请重试");
            }
        });
    }


    /**
     * 标签单次读取
     */
    public void singleReadTag() {

//        ProxyReadTag.getInstance().singleReadTagTid(new ProxyReadTag.ReadTagCallback() {
//
//            @Override
//            public void onReadSuccess(String tid) {
//                mRootView.initTid(tid,"");
//            }
//
//            @Override
//            public void onFailed(String message) {
//                mRootView.showMessage(message);
//            }
//        }, new ProxyReadTag.StopReadCallback() {
//            @Override
//            public void onStopSuccess() {
//
//            }
//
//            @Override
//            public void onStopFailed() {
//                mRootView.showMessage("停止读取标签操作失败，请重试");
//            }
//        });
    }

    /**
     * 将数据存储到服务器
     *
     * @param tid
     * @param cageNo
     * @author shengjunhao edit at 2018/8/14  下午3:36
     */
    public void saveDataToServer(String tid, String tid2, String cageNo) {

        if (tid.length() == 0 || cageNo.length() == 0 || tid.equals("tid1") || tid2.equals("tid2")) {

            saveFailed("TID数据或者笼车编号不可以为空！");
            return;
        }

        RfidCageBind rfidCageBind = queryManager.getRfidCageQuery().queryDataByCageNo(cageNo);
        if (rfidCageBind != null) {

            saveFailed("该笼车编号已绑定！");
            return;
        }

//        RfidCageBind rfidCageBind = queryManager.getRfidCageQuery().queryDataByTid(tid);
//        if (rfidCageBind != null) {
//            saveFailed("该TID已经被绑定");
//            return;
//        }
//        RfidCageBind rfidCageBind1 = queryManager.getRfidCageQuery().queryDataByCageNo(cageNo);
//        if (rfidCageBind1 != null) {
//
//            saveFailed("该笼车编号已经被绑定");
//            mRootView.clearCageNo();
//            return;
//        }

        // 存储到本地
        RfidCageBind rfidCageBindNew = new RfidCageBind();
        rfidCageBindNew.setId(UUIDUtils.getShortUUId());
        rfidCageBindNew.setTagId(tid + Constant.ValueOfSpare + tid2);
        rfidCageBindNew.setCageId(cageNo);
        rfidCageBindNew.setIsBind(false);
//        rfidCageBind.setBindTime("");
        rfidCageBindNew.setBindTime(TimeUtilsNew.getStringTimelByLong(System.currentTimeMillis()));
        rfidCageBindNew.setFailedMessage("");
        queryManager.getRfidCageQuery().insert(rfidCageBindNew);

        if (true) {
            SoundPlayUtils.getInstance().playSound(SoundPlayUtils.SOUNT_SUCCESS, 3);
            mRootView.showMessage("数据存储成功");
            mRootView.clearCageNo();

            return;
        }
        // 存储到服务器
        if (WifiStatueUtils.isWife()) {

            // 用代理方法将数据上传到服务器
            sendData(tid, cageNo, rfidCageBindNew);
        } else {
            // 存储到本地，播放3次失败声音
            SoundPlayUtils.getInstance().playSound(SoundPlayUtils.SOUNT_FAILED, 3);
        }
    }


    /**
     * 根据id来查询绑定关系
     *
     * @param tid
     */
    public void queryBindByTid(String tid) {

        String url = "http://" + Constant.byIp + "/api/CageInfo/CageQuery?tid=" + tid;
        ProxyNetWorker.getInstance().getServerData(url, new ProxyNetWorker.RequestCallback() {
            @Override
            public void onSuccess(String data) {

                mRootView.showMessage(data);
                MyLogUtils.log("test", data, 4);
                MessageEntity messageEntity = (MessageEntity) GsonUtils.jsonToBean(data, MessageEntity.class);

                if (messageEntity == null) {
                    mRootView.showMessage("该笼车未初始化！");
                    return;
                }
                if (messageEntity.getStatus().equals("1")) {
                    mRootView.initCageNo(messageEntity.getInfo());
                    mRootView.showUpdataButton();
                } else {

                    mRootView.showMessage(messageEntity.getInfo());
                }
            }

            @Override
            public void onFailed(String msg) {

                MyLogUtils.log("test", "failed query" + msg, 4);
            }
        });
    }

    /**
     * 根据id来查询绑定关系
     *
     * @param tid
     */
    public void updateTheBind(String tid, String cageNo) {


        if (tid.length() == 0 || cageNo.length() == 0 || tid.equals("tid")) {

            saveFailed("TID数据或者笼车编号不可以为空！");
            return;
        }

        String url = "http://" + Constant.byIp + "/api/CageInfo/CageSCUpdate?tid=" + tid + "&codeName=京烟" + cageNo;
        ProxyNetWorker.getInstance().getServerData(url, new ProxyNetWorker.RequestCallback() {
            @Override
            public void onSuccess(String data) {

                MyLogUtils.log("test", "update_" + data, 4);
                MessageEntity messageEntity = (MessageEntity) GsonUtils.jsonToBean(data, MessageEntity.class);
                if (messageEntity.getStatus().equals("1")) {

                    mRootView.clearCageNo();
                    mRootView.showMessage("更新成功");
                    SoundPlayUtils.getInstance().playSound(SoundPlayUtils.SOUNT_SUCCESS, 3);
                } else {
                    mRootView.showMessage(messageEntity.getInfo());
                }
            }

            @Override
            public void onFailed(String msg) {

                mRootView.showMessage("更新失败--" + msg);
                MyLogUtils.log("test", "update_" + msg, 4);
            }
        });
    }

    /**
     * 将数据写入标签
     */
    public void writeData(String data) {

        if(data.trim().length() == 0){

            mRootView.showMessage("集装箱编号不可以");
            return;
        }


        ProxyReadTag.getInstance().writeDataToEpc(ByteConvertUtils.strToByteArray(data), new ProxyReadTag.WriteTagEpcCallback() {
            @Override
            public void onWriteSuccess() {

                mRootView.showMessage("写入标签成功");
            }

            @Override
            public void onWriteFailed() {

                mRootView.showMessage("写入标签失败");
            }
        });
    }


    /**
     * 网络请求
     */
    private void sendData(String tid, String cageNo, final RfidCageBind rfidCageBind) {

        mRootView.showLoading();
        String url = "http://" + Constant.byIp + "/api/CageInfo/CageInitialize?tid=" + tid + "&cageNo=京烟" + cageNo;
        ProxyNetWorker.getInstance().getServerData(url, new ProxyNetWorker.RequestCallback() {
            @Override
            public void onSuccess(String data) {

                //  {"Status":0,"Info":"笼车RFID编号 12323 已经初始化，请换标签重试"}
                MessageEntity messageEntity = (MessageEntity) GsonUtils.jsonToBean(data, MessageEntity.class);
                if (messageEntity.getStatus().equals("0")) {

                    saveFailed(messageEntity.getInfo());
                    mRootView.clearCageNo();
                } else {
                    SoundPlayUtils.getInstance().playSound(SoundPlayUtils.SOUNT_SUCCESS, 2);
                    mRootView.showMessage("插入成功");
                    mRootView.clearCageNo();
                    mRootView.initTid("tid","");
                    rfidCageBind.setIsBind(true);
                    queryManager.getRfidCageQuery().update(rfidCageBind);
                }
                mRootView.hideLoading();
            }

            @Override
            public void onFailed(String msg) {

                mRootView.showMessage(msg);
                mRootView.hideLoading();
            }
        });
    }

    private void saveFailed(String message) {

        SoundPlayUtils.getInstance().playSound(SoundPlayUtils.SOUNT_FAILED, 0);
        mRootView.showMessage(message);
    }
}
